// 认证模块 - 处理用户登录、注册
import baseAPI from './base.js'
import { recordLog } from '../api-logger.js'

class AuthAPI {
    // 用户注册
    async register(userData) {
        // 检查服务器状态，如果离线则使用本地处理
        const serverStatus = baseAPI.getServerStatus();
        if (!serverStatus.isOnline) {
            return this.handleLocalRegister(userData);
        }
        
        return baseAPI.request('/register', {
            method: 'POST',
            body: JSON.stringify(userData)
        });
    }

    // 用户登录
    async login(credentials) {
        // 检查服务器状态，如果离线则使用本地处理
        const serverStatus = baseAPI.getServerStatus();
        if (!serverStatus.isOnline) {
            return this.handleLocalLogin(credentials);
        }
        
        return baseAPI.request('/login', {
            method: 'POST',
            body: JSON.stringify(credentials)
        });
    }

    // ==================== 本地离线处理 ====================

    // 本地注册处理
    handleLocalRegister(userData) {
        const startTime = Date.now();
        try {
            const users = this.getLocalUsers();
            
            // 检查邮箱是否已存在
            if (users.find(u => u.email === userData.email)) {
                const duration = Date.now() - startTime;
                recordLog({
                    type: 'offline',
                    method: 'POST',
                    url: '/register',
                    status: 'LOCAL',
                    success: false,
                    errorMessage: '该邮箱已被注册',
                    durationMs: duration
                });
                return Promise.reject(new Error('该邮箱已被注册'));
            }
            
            // 创建新用户
            const newUser = {
                id: this.generateUserId(),
                offline_id: this.generateOfflineId(),
                name: userData.name,
                email: userData.email,
                password: userData.password,
                createdAt: new Date().toISOString(),
                role: 'user',
                status: 'active'
            };
            users.push(newUser);
            this.saveLocalUsers(users);
            
            const duration = Date.now() - startTime;
            recordLog({
                type: 'offline',
                method: 'POST',
                url: '/register',
                status: 'LOCAL',
                success: true,
                durationMs: duration
            });
            
            return Promise.resolve({
                message: '注册成功（本地模式）',
                data: { user: newUser }
            });
        } catch (error) {
            const duration = Date.now() - startTime;
            recordLog({
                type: 'offline',
                method: 'POST',
                url: '/register',
                status: 'LOCAL',
                success: false,
                errorMessage: error.message,
                durationMs: duration
            });
            return Promise.reject(error);
        }
    }

    // 本地登录处理
    handleLocalLogin(credentials) {
        const startTime = Date.now();
        try {
            const { email, password } = credentials;
            const users = this.getLocalUsers();
            const user = users.find(u => u.email === email && u.password === password);
            
            if (!user) {
                const duration = Date.now() - startTime;
                recordLog({
                    type: 'offline',
                    method: 'POST',
                    url: '/login',
                    status: 'LOCAL',
                    success: false,
                    errorMessage: '邮箱或密码错误',
                    durationMs: duration
                });
                return Promise.reject(new Error('邮箱或密码错误'));
            }
            
            const duration = Date.now() - startTime;
            recordLog({
                type: 'offline',
                method: 'POST',
                url: '/login',
                status: 'LOCAL',
                success: true,
                durationMs: duration
            });
            
            return Promise.resolve({
                message: '登录成功（本地模式）',
                data: {
                    user: { 
                        id: user.id, 
                        name: user.name, 
                        email: user.email, 
                        role: user.role, 
                        created_at: user.createdAt 
                    },
                    user_id: user.id,
                    user_name: user.name,
                    user_email: user.email,
                    role: user.role,
                    created_at: user.createdAt
                }
            });
        } catch (error) {
            const duration = Date.now() - startTime;
            recordLog({
                type: 'offline',
                method: 'POST',
                url: '/login',
                status: 'LOCAL',
                success: false,
                errorMessage: error.message,
                durationMs: duration
            });
            return Promise.reject(error);
        }
    }

    // ==================== 本地存储辅助方法 ====================

    // 本地用户存取
    getLocalUsers() {
        return JSON.parse(uni.getStorageSync('users') || '[]');
    }
    
    saveLocalUsers(users) {
        uni.setStorageSync('users', JSON.stringify(users));
    }

    // 生成用户ID（支持64位整数）
    generateUserId() {
        const timestamp = Date.now();
        return timestamp.toString();
    }
    
    // 生成离线ID
    generateOfflineId() {
        return Date.now().toString();
    }
}

// 创建全局实例
const authAPI = new AuthAPI();

export default authAPI; 